﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using CID.Domain.Development;
using CID.Domain.Users;
using CID.Web.Models.Development;
using CID.Web.Support;
using NailsFramework.IoC;
using NailsFramework.Persistence;

namespace CID.Web.Controllers
{
    [CIDAuthorize(UserRole.Manager, UserRole.ReleaseManager)]
    public class ReleaseController : BaseCRUDController<IRelease, Release, ReleaseViewModel>
    {
        [Inject]
        public IBag<User> Users { private get; set; }
        public IEnumerable<User> EnabledUsers { get { return Users.Where(x => x.Enabled); } }

        protected override Release CreateModel(ReleaseViewModel viewModel)
        {
            return new Release(viewModel.Name, viewModel.Description, Users.GetById(viewModel.ResponsibleId));
        }

        protected override void PrepareViewModelForView(ReleaseViewModel viewModel)
        {
            base.PrepareViewModelForView(viewModel);

            viewModel.SetAvailableUsers(EnabledUsers);
            if (viewModel.ResponsibleId.HasValue && String.IsNullOrEmpty(viewModel.Responsible))
                viewModel.Responsible = Users.GetById(viewModel.ResponsibleId.Value).Name;
        }

        [HttpPost]
        public RedirectToRouteResult SetActive(int id)
        {
            var release = Entities.GetById(id);
            release.SetActive();
            return RedirectToAction("Index");
        }

        [HttpPost]
        public RedirectToRouteResult SetObsolete(int id)
        {
            var release = Entities.GetById(id);
            release.SetObsolete();
            return RedirectToAction("Index");
        }

        [HttpPost]
        public RedirectToRouteResult SetReleased(int id)
        {
            var release = Entities.GetById(id);
            release.SetReleased();
            return RedirectToAction("Index");
        }
    }
}
